/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
// 这个是自己从解答中抄到的答案
var rightSideView = function (root) {
  if (!root) return [];
  let result = [];

  let queue = [root];

  while (queue.length > 0) {
    let queuelen = queue.length;
    for (let i = 0; i < queuelen; i++) {
      let queueNode = queue.shift();
      if (i === queuelen - 1) {
        result.push(queueNode.val);
      }
      if (queueNode.left) queue.push(queueNode.left);
      if (queueNode.right) queue.push(queueNode.right)
    }
  }
  return result;
};
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
// ai 的回答，使用层序遍历的方式实现右视图
var rightSideView = function (root) {
  if (root === null) {
    return [];
  }

  const result = [];
  const queue = [root];

  while (queue.length > 0) {
    const levelSize = queue.length;

    for (let i = 0; i < levelSize; i++) {
      const current = queue.shift();

      // 每层的最后一个节点是右视图的一部分
      if (i === levelSize - 1) {
        result.push(current.val);
      }

      if (current.left !== null) {
        queue.push(current.left);
      }

      if (current.right !== null) {
        queue.push(current.right);
      }
    }
  }

  return result;
};

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
// ai 的回答使用深度优先遍历的方式实现
var rightSideView = function (root) {
  const result = [];

  function dfs(node, depth) {
    if (node === null) {
      return;
    }

    // 如果当前深度等于结果数组的长度，说明是该层第一个访问的节点
    if (depth === result.length) {
      result.push(node.val);
    }

    // 优先遍历右子树，再遍历左子树
    dfs(node.right, depth + 1);
    dfs(node.left, depth + 1);
  }

  dfs(root, 0);
  return result;
};